package com.xmh.code.generation.util;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.Date;

@Slf4j
public class FileUtil {


    public static void outFile(Date date, String path) {
        try {
            String dateToString = DateUtil.getDateToString(date);

            File file = new File(path);

            if (!file.exists()) {
                file.createNewFile();
            }
            PrintWriter out = new PrintWriter(new FileWriter(file));

            out.write(dateToString);
            out.flush();
            out.close();
        } catch (IOException e) {
            log.error("", e);
        }
    }

    public static void outFile(String data, String path) {
        try {
            File file = new File(path);

            if (!file.exists()) {
                file.createNewFile();
            }
            PrintWriter out = new PrintWriter(new FileWriter(file));

            out.write(data);
            out.flush();
            out.close();
        } catch (IOException e) {
            log.error("", e);
        }
    }

    public static boolean isExist(String path) {
        File file = new File(path);
        return file.exists();
    }

    public static Date getFile(String path) {
        return DateUtil.getStringToDate(getFileStr(path));
    }

    public static String getFileStr(String path) {
        File file = new File(path);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        Reader in = null;

        String string = null;
        FileInputStream in2 = null;
        try {
            in2 = new FileInputStream(file);
            in = new InputStreamReader(in2, "utf-8");
            StringBuffer sBuffer = new StringBuffer();

            int len = -1;
            while ((len = in.read()) != -1) {
                sBuffer.append((char) len);
            }
            in.close();
            string = sBuffer.toString();
        } catch (IOException e) {
            log.error("", e);
            return null;
        } finally {
            try {
                if (in2 != null) {
                    in2.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error("", e);
                return null;
            }
        }
        return string;
    }


    /**
     * 获取到源文件夹里面的文件内容
     *
     * @param classes
     * @param path
     * @return
     */
    public static String getSourceFile(Class<?> classes, String path) {
        return  FileUtil.getFileStr(classes.getResource(path).getPath());
    }
}
